package com.blog.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blog.admin.annotation.BuildCache;
import com.blog.admin.service.PhotoAlbumService;
import com.blog.common.core.enums.FileEnums;
import com.blog.common.core.utils.PageUtils;
import com.blog.common.core.web.page.TableDataInfo;
import com.blog.common.domain.entity.FileInfo;
import com.blog.common.domain.entity.PhotoAlbum;
import com.blog.common.domain.dto.PhotoAlbumDto;
import com.blog.common.domain.vo.PhotoAlbumVo;
import com.blog.common.mapper.dao.FileInfoMapper;
import com.blog.common.mapper.dao.PhotoAlbumMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;

import static com.blog.common.core.constant.CacheConstants.FILE_INFO;

/**
 * <p>
 * 相册 服务实现类
 * </p>
 *
 * @author Valerie
 * @since 2023-03-11
 */
@Service
public class PhotoAlbumServiceImpl extends ServiceImpl<PhotoAlbumMapper, PhotoAlbum> implements PhotoAlbumService {

    @Resource
    private PhotoAlbumMapper photoAlbumMapper;

    @Resource
    private FileInfoMapper fileInfoMapper;

    @Override
    public TableDataInfo<PhotoAlbumVo> listPhotoAlbum() {
        Page<PhotoAlbumVo> photoAlbumVoPage = photoAlbumMapper.listPhotoAlbum(new Page<>(PageUtils.getPageNum(), PageUtils.getPageSize()));
        return new TableDataInfo<>(photoAlbumVoPage.getRecords(), photoAlbumVoPage.getTotal());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @BuildCache(FILE_INFO)
    public Boolean updatePhotoAlbum(PhotoAlbumDto photoAlbumDto) {
        FileInfo fileInfo = FileInfo.builder()
                .id(IdUtil.getSnowflakeNextId())
                .fileName("相册封面")
                .fileType(FileEnums.ALBUM_FILE.getCode())
                .fileName(photoAlbumDto.getAlbumName())
                .filePath(photoAlbumDto.getAlbumCover())
                .build();
        fileInfoMapper.insert(fileInfo);
        PhotoAlbum photoAlbum = BeanUtil.copyProperties(photoAlbumDto, PhotoAlbum.class);
        photoAlbum.setAlbumCover(fileInfo.getId().toString());
        PhotoAlbumService photoAlbumService = SpringUtil.getBean(PhotoAlbumService.class);
        photoAlbumService.saveOrUpdate(photoAlbum);
        return true;
    }

    @Override
    public PhotoAlbumVo listPhotoAlbum(Serializable albumId) {
        PhotoAlbum photoAlbum = photoAlbumMapper.selectOne(new LambdaQueryWrapper<PhotoAlbum>()
                .eq(PhotoAlbum::getId, albumId)
                .last("limit 1")
        );
        return BeanUtil.copyProperties(photoAlbum, PhotoAlbumVo.class);
    }
}
